﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace EAWRC117Installer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static string PAK_FILE_NAME = "CN117_p.pak";
        private static string PAK_ZIP_FILE_NAME = "CN117_p.zip";
        private static string[] OTHER_PAK_FILE_NAMES = { "Kiko_P.pak", "LaoWang_P.pak"};
        public MainWindow()
        {
            InitializeComponent();
            this.MouseDown += (o, e) => { if (e.LeftButton == MouseButtonState.Pressed) DragMove(); };
        }

        private async void btn_install_Click(object sender, RoutedEventArgs e)
        {
            // if installed, change the install button background image to res/installed@4x.png build as "Resource"
            if (!checkIfPakInstalled())
            {
                if (checkIfAppWasInCorrectPath())
                {
                    btn_install.IsEnabled = false;
                    btn_restore.IsEnabled = false;
                    // install
                    // copy res/117_p.pak packaged as "Resource" in wpf to Content\Paks folder in thread
                    await Task.Run(() =>
                    {
                        // change button background to installing
                        Dispatcher.Invoke(() =>
                        btn_install.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/installing@4x.png"))));

                        // remove other pak files if exists
                        foreach (var pakFileName in OTHER_PAK_FILE_NAMES)
                        {
                            if (System.IO.File.Exists($"WRC\\Content\\Paks\\{pakFileName}"))
                            {
                                File.Delete($"WRC\\Content\\Paks\\{pakFileName}");
                            }
                        }

                        // write the resource to file
                        WriteResourceToFile($"EAWRC117Installer.res.{PAK_ZIP_FILE_NAME}", $"WRC\\Content\\Paks\\{PAK_ZIP_FILE_NAME}");

                        // unzip the file
                        System.IO.Compression.ZipFile.ExtractToDirectory($"WRC\\Content\\Paks\\{PAK_ZIP_FILE_NAME}", "WRC\\Content\\Paks");

                        // remove zip file
                        File.Delete($"WRC\\Content\\Paks\\{PAK_ZIP_FILE_NAME}");
                    });
                    // change the install button background image when task finished
                    btn_install.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/installed@4x.png")));
                    btn_restore.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/reset@4x.png")));
                    btn_install.IsEnabled = true;
                    btn_restore.IsEnabled = true;
                } else
                {
                    // show error message
                    MessageBox.Show("请将本程序放置在游戏根目录下运行，即包含WRC和Engine文件夹的目录。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
        }

        private bool checkIfPakInstalled()
        {
            // check if there is file 117_p.pak in Content\Paks folder
            bool result = false;
            if (System.IO.File.Exists($"WRC\\Content\\Paks\\{PAK_FILE_NAME}"))
            {
                result = true;
            }
            return result;
        }
        
        private bool checkIfAppWasInCorrectPath()
        {
            // the current executable file path should be in the game folder
            // which contains the Content\Paks folder and Binaries folder
            bool result = false;
            if (System.IO.Directory.Exists("WRC\\Content\\Paks") && System.IO.Directory.Exists("Engine\\Binaries"))
            {
                result = true;
            }
            return result;
        }

        public void WriteResourceToFile(string resourceName, string fileName)
        {
            using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                using (var file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    resource.CopyTo(file);
                }
            }
        }

        private void btn_linkhanhuatool_Click(object sender, RoutedEventArgs e)
        {
            // browser open https://gitee.com/ztmz/ea_wrc_chinese_translation/releases
            System.Diagnostics.Process.Start("https://gitee.com/ztmz/ea_wrc_chinese_translation/releases");
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (checkIfPakInstalled())
            {
                btn_install.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/installed@4x.png")));
                btn_restore.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/reset@4x.png")));
            }
            
        }

        private async void btn_restore_Click(object sender, RoutedEventArgs e)
        {
            if (!checkIfPakInstalled())
            {
                return;
            }
            btn_restore.IsEnabled = false;
            // remove 117_p.pak in Content\Paks folder 
            await Task.Run(() => File.Delete($"WRC\\Content\\Paks\\{PAK_FILE_NAME}"));
            // change the install button background image when task finished
            btn_restore.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/reset_done@4x.png")));
            btn_install.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/EAWRC117Installer;component/res/install_button@4x.png")));
            btn_restore.IsEnabled = true;
        }

        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {
            tb_info.Visibility = Visibility.Visible;
        }

        private void Image_MouseLeave(object sender, MouseEventArgs e)
        {
            tb_info.Visibility = Visibility.Hidden;
        }
    }
}
